package service

import (
	"errors"
	"gorm.io/gorm"
	"tdy-backend/app/core/service"
	"tdy-backend/app/panoramic/dto"
	"tdy-backend/app/panoramic/model"
)

type GroupService struct {
	service.BaseService
}

//新增分组
func (o *GroupService) Add(param *dto.GroupAddDto) (*model.Group, error) {
	group := model.Group{}
	db := o.DB
	works := model.Works{}
	worksInfo := db.Model(&works).Where("id=?", param.WorksId).Where("member_id=?", o.MemberInfo.ID).First(&works)
	if errors.Is(worksInfo.Error, gorm.ErrRecordNotFound) {
		return nil, errors.New("作品不存在")
	}
	groupDefault := model.Group{}
	groupInfo := db.Model(&groupDefault).Where("works_id=?", param.WorksId).Where("is_default=?", 1).First(&groupDefault)
	group.IsDefault = param.IsDefault
	//如果该作品下无分组，强制设置为默认分组
	if errors.Is(groupInfo.Error, gorm.ErrRecordNotFound) {
		group.IsDefault = 1
	} else {
		//如果设置默认分组 将其他分组设置为普通分组
		if param.IsDefault == 1 {
			groupDefault.IsDefault = 2
			db.Select("is_default").Save(&groupDefault)
		}
	}
	group.WorksId = param.WorksId
	group.Title = param.Title

	group.MemberId = o.MemberInfo.ID

	create := db.Create(&group)
	if create.Error != nil {
		return nil, errors.New("分组创建失败")
	}
	return &group, nil
}

//编辑分组
func (o *GroupService) Edit(param *dto.GroupEditDto) (*model.Group, error) {
	group := model.Group{}
	db := o.DB
	groupInfo := db.Model(&group).Where("id=?", param.ID).Where("member_id=?", o.MemberInfo.ID).First(&group)
	if errors.Is(groupInfo.Error, gorm.ErrRecordNotFound) {
		return nil, errors.New("分组不存在")
	}
	updateData := map[string]interface{}{}
	if param.IsDefault == 1 && group.IsDefault != 1 {
		groupDefault := model.Group{}
		groupDefaultInfo := db.Model(&groupDefault).
			Where("works_id=?", group.WorksId).
			Where("is_default=?", 1).
			First(&groupDefault)
		if !errors.Is(groupDefaultInfo.Error, gorm.ErrRecordNotFound) {
			groupDefault.IsDefault = 2
			db.Model(&groupDefault).Save(&groupDefault)
		}
		updateData["is_default"] = param.IsDefault
	} else {
		updateData["is_default"] = param.IsDefault
	}
	updateData["title"] = param.Title

	updates := db.Model(&group).Updates(updateData)
	if updates.Error != nil {
		return nil, updates.Error
	}
	return &group, nil
}

//删除分组
func (o *GroupService) Delete(param *dto.GroupDeleteDto) error {
	groups := []model.Group{}
	db := o.DB
	groupsInfo := db.Where("id IN ?", param.Ids).Where("member_id=?", o.MemberInfo.ID).Find(&groups)
	if groupsInfo.RowsAffected == 0 {
		return errors.New("分组数据不存在")
	}
	for _, group := range groups {
		if group.IsDefault == 1 {
			return errors.New("默认分组无法删除")
		}
	}
	db.Delete(&groups)
	return nil
}

//列表分组
func (o *GroupService) ListAll(param *dto.GroupListDto) *[]model.Group {
	//logger := global.TYD_LOGGER
	db := o.DB
	groupList := []model.Group{}

	db = db.Where("works_id=?", param.WorksId).Where("member_id=?", o.MemberInfo.ID)
	db.Order("id asc").Find(&groupList)

	return &groupList
}
